package com.study.springbootsecurity.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-04 21:31
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class LoginUser implements UserDetails {
    /**
     * 存储SpringSecurity所需要的权限信息的集合
     * redis为了安全考虑,不会序列化spring中的对象，权限信息敏感，不能添加redis
     * 表示在将该对象转换为JSON字符串时，不包含该字段的内容
     */
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    // 用户具有权限
    private List<String> permissions;
    private SysUser sysUser;

    public LoginUser(SysUser sysUser,List<String> permissions) {
        this.permissions = permissions;
        this.sysUser = sysUser;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(authorities)) {
            authorities = new ArrayList<>();
            for (String permission : permissions) {
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission);
                authorities.add(grantedAuthority);
            }
            return authorities;
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return sysUser.getAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return sysUser.getAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return sysUser.getCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return sysUser.getEnabled();
    }
}
